/**
 * 选择地区
 */

import React, { useState, useEffect } from 'react';
import CommonModal from '@/components/CommonModal';
import { Spin, Checkbox, Divider, Empty, message } from 'antd';
import { cloneDeep, find, findIndex } from 'lodash';
import { getAllArea } from '@/services/common';
import { getCanSelectArea } from '../../service';
import styles from './index.module.less';

export default ({ id, item, visible, handleOk, handleCancel }) => {

  const [ data, setData ] = useState([]);
  const [ loading, setLoading ] = useState(false);
  const [ provinceId, setProvinceId ] = useState(undefined);
  const [ cityId, setCityId ] = useState(undefined);
  const [ selectData, setSelectData ] = useState([]);

  useEffect(() => {
    if(visible) {
      getAreaData();
      setSelectData(item.newSelectId);
    }
  }, [visible])

  const getAreaData = async () => {
    setLoading(true);
    let res;
    if(id) {
      res = await getCanSelectArea({ areaIds: id });
    } else {
      res = await getAllArea();
    }
    if(res.success) {
      setData(res.data);
    }
    setLoading(false);
  }

  const onOk = () => {
    if(loading) {
      return false;
    }
    handleOk(selectData);
    onCancel();
  }

  const onCancel = () => {
    handleCancel();
    setData([]);
    setProvinceId(undefined);
    setCityId(undefined);
    setSelectData([]);
  }

  //选择省份
  const handleSelectProvince = (e, id) => {
    if(id > 100) {
      message.warning('暂不支持该区域');
      return;
    }
    let checked = e.target.checked;
    if(checked) {//全选市
      const obj = find(data, ['id', id]);
      const arr = cloneDeep(selectData);
      const index = findIndex(arr, ['id', id]);
      if(index > -1) {
        arr[index] = obj;
      } else {
        arr.push(obj);
      }
      setSelectData(arr);
      handleClickProvince(id);
    } else {
      const arr = cloneDeep(selectData);
      const index = findIndex(arr, ['id', id]);
      arr.splice(index, 1);
      setSelectData(arr);
      handleClickProvince(id);
    }
  }

  //选择市
  const handleSelectCity = (e, id) => {
    let checked = e.target.checked;
    if(checked) {//全选区
      //查询到省
      const obj = find(data, ['id', provinceId]);
      //查询到市
      const obj1 = find(obj.childs, ['id', id]);

      const index1 = findIndex(selectData, ['id', provinceId]);
      if(index1 > -1) {//如果已选列表包含当前省
        const index2 = findIndex(selectData[index1].childs, ['id', id]);
        const arr = cloneDeep(selectData);
        if(index2 > -1) {//如果已选包含当前市
          arr[index1].childs[index2] = obj1;
        } else {
          arr[index1].childs.push(obj1);
        }
        setSelectData(arr)
      } else {
        const arr = cloneDeep(selectData);
        const arr1 = [];
        arr1.push(obj1);
        const obj = {
          id: provinceId,
          name: find(data, ['id', provinceId]).name,
          childs: arr1,
        }
        arr.push(obj);
        setSelectData(arr);
      } 
    } else {//取消全选
      const arr = cloneDeep(selectData);
      const index1 = findIndex(selectData, ['id', provinceId]);
      const index2 = findIndex(selectData[index1].childs, ['id', id]);
      arr[index1].childs.splice(index2, 1);
      setSelectData(arr);
    }
  }

  //选择区
  const handleSelectArea = (e, id) => {
    let checked = e.target.checked;
    if(checked) {//选择
      const index = findIndex(selectData, ['id', provinceId]);
      if(index > -1) {//已选列表包含当前省
        const index1 = findIndex(selectData[index].childs, ['id', cityId]);
        if(index1 > -1) {//已选列表包含当前市
          const obj = {
            id: id
          }
          const arr = cloneDeep(selectData);
          arr[index].childs[index1].childs.push(obj);
          setSelectData(arr);
        } else {
          const arr = [];
          arr.push({ id: id });
          const obj = {
            id: cityId,
            childs: arr
          }
          const list = cloneDeep(selectData);
          list[index].childs.push(obj);
          setSelectData(list);
        }
      } else {
        const arr = [];
        arr.push({ id });
        const obj = {
          id: cityId,
          childs: arr
        }
        const arr1 = [];
        arr1.push(obj);
        const obj1 = {
          id: provinceId,
          name: find(data, ['id', provinceId]).name,
          childs: arr1
        }
        const list = cloneDeep(selectData);
        list.push(obj1);
        setSelectData(list);
      }
    } else {//取消选择
      const index1 = findIndex(selectData, ['id', provinceId]);
      const index2 = findIndex(selectData[index1].childs, ['id', cityId]);
      const index3 = findIndex(selectData[index1].childs[index2].childs, ['id', id]);
      const arr = cloneDeep(selectData);
      arr[index1].childs[index2].childs.splice(index3, 1);
      setSelectData(arr);
    }
  }

  //查看省份
  const handleClickProvince = (id) => {
    if(id == provinceId) {
      return;
    }
    if(id > 100) {
      message.warning('暂不支持该区域');
      return;
    }
    const arr = find(data, [ 'id', id ]).childs;
    setProvinceId(id);
    setCityId(arr[0].id);
  }

  //查看市
  const handleClickCity = (id) => {
    if(id == cityId) {
      return;
    }
    setCityId(id);
  }

  //判断省是否全选
  const getProvinceChecked = (id) => {
    const index = findIndex(selectData, ['id', id]);
    if(index > -1) {
      const arr1 = find(data, ['id', id]).childs;
      const arr2 = selectData[index].childs;
      if(arr1.length == arr2.length) {
        return true;
      } else {
        return false;
      }
    } else {
      return false;
    }
  }

  //判断市是否全选
  const getCityChecked = (id) => {
    const index1 = findIndex(selectData, ['id', provinceId]);
    if(index1 == -1) {
      return false;
    }
    const arr = find(selectData, ['id', provinceId]).childs;
    const index = findIndex(arr, ['id', id]);
    if(index > -1) {
      const arr1 = find(find(data, ['id', provinceId]).childs, ['id', id]).childs;
      const arr2 = find(arr, ['id', id]).childs;
      if(arr1.length == arr2.length) {
        return true;
      } else {
        return false;
      }
    } else {
      return false;
    }
  }

  //判断区是否是选择
  const getAreaChecked = (id) => {
    //首先判断是否是否有该省份
    const index1 = findIndex(selectData, ['id', provinceId]);
    if(index1 == -1) {
      return false;
    } else {
      //其次判断是否有该市区
      const index2 = findIndex(selectData[index1].childs, ['id', cityId]);
      if(index2 == -1) {
        return false;
      } else {
        const index3 = findIndex(selectData[index1].childs[index2].childs, ['id', id]);
        if(index3 > -1) {
          return true;
        }
        return false;
      }
    }
  }

  //显示市是否全选
  const handleSelectAllCity = (id) => {
    const cityData = find(selectData, ['id', provinceId]);
    if(cityData) {
      let num2 = find(cityData.childs, ['id', id]) ? find(cityData.childs, ['id', id]).childs.length : undefined;
      if(num2) {
        const cityData1 = find(data, ['id', provinceId]).childs;
        let num1 = find(cityData1, ['id', id]).childs.length;
        if(num2 < num1) {
          return true;
        }
        return false;
      }
    } else {
      return false;
    }
  }

  //渲染市列表
  const renderCity = () => {
    if(provinceId) {
      const arr = find(data, ['id', provinceId ]).childs;
      return (
        <div style={{ lineHeight: '32px', overflow: 'auto' }}>
          {
             arr.map(v => (
              <span style={{ margin: '0px 8px', display: 'inline-block' }} key={v.id}>
                <Checkbox indeterminate={handleSelectAllCity(v.id)} checked={getCityChecked(v.id)} onClick={e => handleSelectCity(e, v.id)}  />
                <span className={v.id == cityId ? styles.select : styles.normal} onClick={() => handleClickCity(v.id)} key={v.id}>{v.name}{getCityNum(v.id)}</span>
              </span>
             ))
          }
        </div>
      )
    } else {
      return (
        <div style={{ height: '250px' }}>
          <Empty  description='请选择省份' />
        </div>
      )
    }
  }

  //渲染区域列表
  const renderArea = () => {
    if(cityId) {
      const arr = find(data, ['id', provinceId ]).childs;
      const arr1 = find(arr, [ 'id', cityId ]).childs;
      return (
        <div style={{ lineHeight: '32px', overflow: 'auto' }}>
          {
             arr1.map(v => (
              <span key={v.id} style={{ margin: '0 8px' }}>
                <Checkbox checked={getAreaChecked(v.id)} onClick={e => handleSelectArea(e, v.id)}>{v.name}</Checkbox>
              </span>
            ))
          }
        </div>
      )
    } else {
      return (
        <div>
          <Empty description='请选择市' />
        </div>
      )
    }
  }


  //计算该省份选择市的数量
  const getProvinceNum = id => {
    const obj = find(selectData, ['id', id]);
    if(obj) {
      return `（${obj.childs.length}）`;
    }
    return `（0）`;
  }

  //计算该城市选择区的数量
  const getCityNum = id => {
    const obj = find(selectData, ['id', provinceId]);
    if(obj) {
      const obj1 = find(obj.childs, ['id', id]);
      if(obj1) {
        return `（${obj1.childs.length}）`;
      }
      return `（0）`;
    }
    return `（0）`;
  }

  //显示省是否全选
  const handleSelectAllProvince = (id) => {
    let num2 = find(selectData, ['id', id]) ? find(selectData, ['id', id]).childs.length : undefined;
    if(num2) {
      let num1 = find(data, ['id', id]).childs.length;
      if(num2 < num1) {
        return true;
      }
      return false;
    }
    return false;
  }

  return (
    <CommonModal
      title='选择区域'
      visible={visible}
      width='900px'
      onOk={onOk}
      onCancel={onCancel}
    >
      <Spin spinning={loading}>
        {
          (id && data.length == 0) ?
          <Empty description='当前无可用区域' />
          :
          <div className="flex">
            <div style={{ width: '260px', overflow: 'auto' }}>
              <h3>省列表：</h3>
              <div style={{ display: 'flex', flexWrap: 'wrap' }}>
                {
                  data.map(v => (
                    <div key={v.id} style={{ width: '120px', margin: '2px 4px'}}>
                      <Checkbox indeterminate={handleSelectAllProvince(v.id)} checked={getProvinceChecked(v.id)} onClick={e => handleSelectProvince(e, v.id)} />
                      <span  className={ v.id == provinceId ? styles.select : styles.normal } onClick={() => handleClickProvince(v.id)}  key={v.id}>{v.name}{getProvinceNum(v.id)}</span>
                    </div>
                  ))
                }
              </div>
            </div>
            <Divider type='vertical' style={{ height: '520px', marginRight: '24px', borderWidth: '4px' }} />
            <div style={{ flex: '1' }}>
              <h3>市列表：</h3>
              {renderCity()}
              <Divider />
              <h3>区列表：</h3>
              {renderArea()}
            </div>
          </div>
        }
      </Spin>
    </CommonModal>
  )
}